package team.bluepen.supermarket.service;

import org.springframework.stereotype.Service;
import team.bluepen.supermarket.conf.KafkaProperties;
import team.bluepen.supermarket.data.database.SupermarketSystemDatabase;
import team.bluepen.supermarket.data.database.dao.ProductIdAmountDao;
import team.bluepen.supermarket.data.entity.ProductIdAmount;
import team.bluepen.supermarket.kafka.KafkaReceiveCallback;
import team.bluepen.supermarket.kafka.KafkaReceiver;
import team.bluepen.supermarket.kafka.KafkaTopics;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Cheng
 */
@Service
public class ProductIdAmountRecvService implements KafkaReceiveCallback<ProductIdAmount> {
    private final KafkaReceiver<ProductIdAmount> receiver;

    private final ProductIdAmountDao productIdAmountDao;

    private final Map<Long, Integer> productIdAmount = new HashMap<>();
    private final Map<Long, ProductIdAmount> amountMap = new HashMap<>();

    public ProductIdAmountRecvService(KafkaProperties kafkaProperties,
                                      SupermarketSystemDatabase database) {
        receiver = new KafkaReceiver<>(
                KafkaTopics.STATE_DATA_TOPIC,
                kafkaProperties.getBootstrapServers(),
                "ProductIdAmountRecvServ",
                DataKeys.PRODUCT_ID_COUNT,
                ProductIdAmount.deserializer(),
                this);
        this.productIdAmountDao = database.getProductIdAmountDao();
        receiver.start();
    }

    public Map<Long, Integer> getProductIdAmount() {
        return productIdAmount;
    }

    public Collection<ProductIdAmount> getAmounts() {
        return amountMap.values();
    }

    @Override
    public void onReceive(ProductIdAmount data) {
        productIdAmount.put(data.getId(), data.getAmount());
        amountMap.put(data.getId(), data);

        productIdAmountDao.insert(data);
    }
}
